<!-- 安全管理机构 -->
<template>
  <div>
    <div
      v-show="!editForm"
      shadow
      style="height: 100%; width: 100%; overflow: hidden"
    >
      <div class="department-outer">
        <div class="ct-btns">
          <el-button
            type="primary"
            style="float: right; margin: 10px"
            @click="handleEdit"
            v-hasPermi="['base:institutions:edit']"
            >编辑</el-button
          >
          <el-button
            type="primary"
            style="float: right; margin: 10px"
            @click="handleRefresh"
            >刷新</el-button
          >
        </div>
        <div class="view-box" style="margin-top: 30px">
          <org-view
            v-if="data"
            :data="data"
            :zoom-handled="zoomHandled"
            @on-menu-click="handleMenuClick"
          ></org-view>
        </div>
      </div>
    </div>
    <!-- 点击机构打开详情信息 -->
    <el-drawer
      :title="this.messageForm.name"
      :visible.sync="addMessageForm"
      size="350px"
      style="height: 80%; margin-top: 70px"
    >
    <div style="background: #abd7ff; line-height: 40px;padding:10px 0 10px 20px;">{{ messageForm.name }}</div>
      <div style="margin: 20px  20px 0; overflow-y: scroll">
        <div style="display: flex; justify-content: space-between">
          <span> 部门/岗位名称： </span>
          <span>
            {{ institutionInfo.name }}
          </span>
        </div>
        <el-divider></el-divider>
        <div style="display: flex; justify-content: space-between">
          <span>责任人：</span>
          <span>{{ institutionInfo.dutyPersonName }}</span>
        </div>
        <el-divider></el-divider>
        <div style="display: flex; justify-content: space-between">
          <span>联系电话：</span>
          <span>{{ institutionInfo.phone }}</span>
        </div>
        <el-divider></el-divider>
        <div style="display: flex; justify-content: space-between">
          <span>职责：</span>
          <span>{{ institutionInfo.duty }}</span>
        </div>
        <el-divider></el-divider>
        <div v-if="teamList.length > 0" style="overflow-y: scroll;height: 500px;">
          <div style="margin: 15px 0;">队伍成员</div>
          <div style="display: flex; justify-content: space-between">
            <span>姓名</span>
            <span>联系方式</span>
          </div>
          <el-divider></el-divider>
          <div v-for="(item, index) in teamList" :key="index">
            <div
              style="
                display: flex;
                justify-content: space-between;
                margin: 8px 0;
              "
            >
              <span>{{ item.name ? item.name : "-" }}</span>
              <span>{{ item.contact ? item.contact : "-" }}</span>
            </div>
            <el-divider></el-divider>
          </div>
        </div>
      </div>
    </el-drawer>
    <!-- 点击编辑按钮 -->
    <div v-show="editForm">
      <el-card class="app-container">
        <div style="display: flex; flex-direction: row">
          <div style="line-height: 30px; margin-right: 5px">
            <i @click="close" class="el-icon-arrow-left" size="parimay"></i>
          </div>
          <div class="itemTitle">安全管理机构</div>
        </div>
        <div>
          <el-form :inline="true" :model="queryParams" ref="queryForm">
            <!-- <el-col :span="5"> -->
            <el-form-item label="安全管理机构名称" prop="name">
              <el-input
                v-model="queryParams.name"
                placeholder="请输入安全管理机构名称"
                clearable
              />
            </el-form-item>
            <!-- </el-col> -->
            <!-- <el-col :span="5"> -->
            <el-form-item>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
            <!-- </el-col> -->
          </el-form>
        </div>
        <div class="content">
          <div class="ct-btns">
            <el-button
              type="primary"
              @click="handleAdd"
              v-hasPermi="['base:institutions:add']"
              style="margin-bottom: 10px"
              >新增</el-button
            >
          </div>
          <div style="height: 68vh" class="ct-table">
            <elTables
              :currentPage="queryParams.pageNum"
              :table-data="tableData"
              :columns="tableColumns"
              :totalLength="total"
              :handle-current-change="handleCurrentChange"
              isPagin
              :curHeight="tableHeight"
            />
          </div>
        </div>
        <!-- 新增安全管理机构弹框 -->
        <el-dialog
          :title="title"
          :visible.sync="open"
          append-to-body
          @close="cancel"
          class="dialog-form"
        >
          <el-form ref="form" :model="form" :rules="rules" label-width="140px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="名称" prop="name">
                  <el-input
                    v-model="form.name"
                    placeholder="请输入名称"
                    :readonly="!isEdit"
                    :disabled="!isEdit"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="机构分类" prop="type">
                  <el-select
                    v-model="form.type"
                    placeholder="请选择机构分类"
                    clearable
                    :readonly="!isEdit"
                    :disabled="!isEdit"
                  >
                    <el-option
                      v-for="(dict, index) in typeList"
                      :key="index"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="上级机构" prop="parent">
                  <el-select
                    v-model="form.parent"
                    placeholder="请选择上级机构"
                    clearable
                    :readonly="!isEdit"
                    :disabled="!isEdit"
                  >
                    <el-option
                      v-for="(dict, index) in parentList"
                      :key="index"
                      :label="dict.name"
                      :value="dict.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="岗位名称"
                  prop="parent"
                  v-if="form.type == 0"
                >
                  <el-select
                    v-model="form.deptId"
                    placeholder="请选择岗位"
                    clearable
                    :readonly="!isEdit"
                    :disabled="!isEdit"
                  >
                    <el-option
                      v-for="(dict, index) in postList"
                      :key="index"
                      :label="dict.postName"
                      :value="dict.postId"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="部门名称" prop="deptId" v-else>
                  <deptAndDuty
                    type-show="dept"
                    @deptChange="deptChange"
                    :deptId="form.deptId"
                    :disabled="!isEdit"
                  ></deptAndDuty>
                </el-form-item>
              </el-col>
            </el-row>
            <el-col :span="12">
              <el-form-item label="负责人" prop="dutyPerson">
                <deptAndDuty
                  type-show="duty"
                  @dutyChange="dutyChange"
                  :dutyId="form.dutyPerson"
                  :disabled="!isEdit"
                ></deptAndDuty>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="职责" prop="duty">
                <el-input
                  v-model="form.duty"
                  type="textarea"
                  placeholder="请输入内容"
                  :readonly="!isEdit"
                  :disabled="!isEdit"
                />
              </el-form-item>
            </el-col>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </div>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
const defaultQueryParams = {
  pageNum: 1,
  pageSize: 10,
};
import {
  listInstitutions,
  getInstitutions,
  getTree,
  pageInstitutions,
  delInstitutions,
  updateInstitutions,
  addInstitutions,
} from "@/api/safetyManagement/info/institution";
import { listTeam } from "@/api/safetyManagement/info/teamRecord";
import OrgView from "@/components/orgTree/org-view.vue";
import ZoomController from "@/components/orgTree/zoom-controller.vue";
import "@/components/orgTree/safetyManageOrg.less";
import { listUser } from "@/api/system/user.js";
import { listPost } from "@/api/system/post";
import { listDept } from "@/api/system/dept";
const menuDic = {
  edit: "编辑按钮",
  detail: "查看按钮",
  new: "新增按钮",
  delete: "删除按钮",
};
export default {
  name: "org_tree_page",
  components: {
    OrgView,
    ZoomController,
  },
  data() {
    return {
      parentList: [],
      typeList: [],
      isEdit: true,
      // 表单校验
      rules: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        type: [
          { required: true, message: "机构分类不能为空", trigger: "change" },
        ],
        parent: [
          { required: true, message: "父级id不能为空", trigger: "blur" },
        ],
        dutyPerson: [
          { required: true, message: "负责人id不能为空", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "部门或岗位id不能为空", trigger: "blur" },
        ],
        duty: [{ required: true, message: "职责不能为空", trigger: "blur" }],
      },
      form: {},
      title: "",
      tableData: [{}, {}],
      total: 0,
      tableHeight: 0,
      queryParams: {
        ...defaultQueryParams,
      },
      institutionInfo: [],
      teamList: [],
      institutionTitle: "机构名称",
      // TODO 目前暂时为假数据，可调用接口方法赋予实时数据
      data: {},
      open: false,
      tableColumns: [
        { key: "name", title: "安全管理机构名称" },
        { key: "parentName", title: "上级机构" },
        { key: "deptName", title: "岗位/部门名称" },
        { key: "dutyPersonName", title: "负责人" },
        {
          title: "操作",
          width: 260,
          render: (h, params) => {
            return h("div", [
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["base:institutions:info"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 2);
                    },
                  },
                },
                "查看队伍档案"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["base:institutions:edit"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 1);
                    },
                  },
                },
                "编辑"
              ),

              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["base:institutions:delete"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleDelete(params.row);
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ],
      editForm: false,
      zoom: 100,
      addMessageForm: false,
      messageForm: {},
      listUser: [], //人员列表
      postList: [], //岗位列表
      deptOptions: [],
    };
  },
  created() {
    this.getDicts("institution_type").then((response) => {
      this.typeList = response.data;
    });
    listUser().then((res) => {
      this.listUser = res.rows;
    });
    listPost().then((response) => {
      this.postList = response.rows;
    });
    listDept().then((response) => {
      this.deptOptions = response.data;
    });
  },
  computed: {
    zoomHandled() {
      return this.zoom / 100;
    },
  },
  mounted() {
    this.getList();
    this.$nextTick(() => {
      this.getTableHeight();
    });
  },
  methods: {
    getInstitution() {
      listInstitutions().then((res) => {
        this.parentList = res.data;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          let data;
          if (Array.isArray(ids)) {
            data = ids;
          } else {
            data = [ids];
          }
          return delInstitutions(data);
        })
        .then(() => {
          this.pageInstitutions();
          this.msgSuccess("删除成功");
        });
    },
    handleUpdate(row, type) {
      if (type == 1) {
        this.isEdit = true;
        this.title = "编辑安全管理机构";
      } else {
        this.$router.push({
          query: { institutionId: row.id },
          path: "/SafetyManagement/safetyInfo/teamRecord",
        });
      }
      this.reset();
      const id = row.id || this.ids;
      getInstitutions(id).then((response) => {
        this.$nextTick(() => {
          this.form = response.data;
          this.open = true;
        });
      });
    },
    /** 查询安全管理机构列表 */
    pageInstitutions() {
      this.loading = true;
      pageInstitutions(this.queryParams).then((response) => {
        this.tableData = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        type: null,
        parent: null,
        dutyPerson: null,
        deptId: null,
        deptName: null,
        duty: null,
        factoryId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        createDept: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    getTeamList(id) {
      listTeam({ institutionsId: id }).then((response) => {
        console.log(response);
        this.teamList = response.data;
      });
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.pageInstitutions();
    },
    close() {
      this.editForm = false;
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.pageInstitutions();
    },
    // 组件传回的部门id
    deptChange(val) {
      this.form.deptId = val;
    },
    // 组件传回的人员id
    dutyChange(val) {
      this.form.dutyPerson = val;
    },
    getTableHeight() {
      let height = document.getElementsByClassName("ct-table")[0].clientHeight;
      this.tableHeight = height - 40;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm() {
      this.form.dutyPersonName = this.listUser.find(
        (o) => o.userId == this.form.dutyPerson
      ).nickName;
      if (this.form.type == 0) {
        this.form.deptName = this.postList.find(
          (o) => o.postId == this.form.deptId
        ).postName;
      } else {
        this.form.deptName = this.deptOptions.find(
          (o) => o.deptId == this.form.deptId
        ).deptName;
      }
      this.form.parentName = this.parentList.find(
        (o) => o.id == this.form.parent
      ).name;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateInstitutions(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.pageInstitutions();
              this.getList();
            });
          } else {
            addInstitutions(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.pageInstitutions();
              this.getList();
            });
          }
        }
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getInstitution();
      this.open = true;
      this.title = "新增安全管理机构";
    },
    handleEdit() {
      this.editForm = true;
      this.addMessageForm = false;
      this.getInstitution();
      this.pageInstitutions();
    },
    handleRefresh() {
      this.getList();
    },
    getList() {
      getTree().then((res) => {
        this.data = {
          id: res.data[0].id,
          label: res.data[0].name,
          children: this.normalizer(res.data[0].childs),
        };
      });
    },
    normalizer(node) {
      if (node && node.length > 0) {
        let data = node.map((v) => {
          return {
            id: v.id,
            label: v.name,
            children: this.normalizer(v.childs),
          };
        });
        return data;
      }
    },
    setDepartmentData(data) {
      data.isRoot = true;
      return data;
    },
    handleMenuClick({ data, key }) {
      console.log(data);
      this.messageForm.name = data.label;
      this.editForm = false;
      const institutionId = data.id;
      this.getTeamList(data.id);
      getInstitutions(institutionId).then((response) => {
        this.institutionInfo = response.data;
        this.institutionTitle = response.data.name;
        this.addMessageForm = true;
      });
      // this.$message(`点击了《${data.label}》节点的'${menuDic[key]}'菜单`);
    },
  },
};
</script>
<style lang="less" scoped>
.infoBox {
  width: 20%;
  height: 400px;
  float: right;
  margin-top: 50px;
  border-bottom: 1px solid gray;
  overflow: hidden;
}
.el-divider--horizontal {
  margin: 15px 0 !important;
}
::v-deep .el-drawer__header {
  margin-bottom: 0 !important;
  display: none !important;
}
</style>
